package com.coincalf.wallet.blockchain.util;

import com.alibaba.fastjson.JSON;
import com.coincalf.wallet.blockchain.BlockException;
import com.coincalf.wallet.blockchain.bean.BaseRPCResponse;
import com.googlecode.jsonrpc4j.JsonRpcHttpClient;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

@SuppressWarnings({"unused", "FieldCanBeLocal"})
public class RpcHttpUtil {

    private static final Logger log = LoggerFactory.getLogger(RpcHttpUtil.class);

    private JsonRpcHttpClient mClient;

    public RpcHttpUtil() {
        String cred = Base64.encodeBase64String(("assetusdtuser:assetJsYTgofkhYienFOOmOs").getBytes());
        Map<String, String> headers = new HashMap<>(1);
        headers.put("Authorization", "Basic " + cred);
        try {
            this.mClient = new JsonRpcHttpClient(new URL("http://127.0.0.1:2203"), headers);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 网络请求和数据处理
     *
     * @param: [method, var] 方法&参数
     * @return: java.lang.String 结果
     **/
    public String engine(String method, Object... var) {
        return engine(method, String.class, var);
    }

    public <T> T engine(String method, Class<T> clazz, Object... var) {
        try {
            return mClient.invoke(method, var, clazz);
        } catch (Throwable throwable) {
            String message = throwable.getMessage();
            Throwable cause = throwable.getCause();
            log.error(cause == null ? "error cause=null" : "error cause=" + cause.getMessage());
            log.error("error message=" + throwable.getMessage());
            try {
                BaseRPCResponse res = JSON.parseObject(message, BaseRPCResponse.class);
                BaseRPCResponse.ErrorBean error = res.getError();
                throw new BlockException(error.getMessage());
            } catch (Exception e) {
                e.printStackTrace();
                throw new BlockException(e.getMessage());
            }
        }
    }

}
